package cli;

import java.util.ArrayList;

public class SelectWidget<T> {
	private String question;
	private ArrayList<T> options;
	private StringBuilder stringBuilder;
	private InputWidget inputWidget = new InputWidget("? ");
	private T selectedOption = null;
	
	public SelectWidget(String question, ArrayList<T> options) {
		this.question = question;
		this.options = options;
		
		this.refresh();
	}
	
	public void refresh() {
		this.stringBuilder = new StringBuilder();
		this.stringBuilder.append(this.question);
		this.stringBuilder.append(CLI.NEWLINE);
		
		for (int i = 0; i < this.options.size(); i++) {
			this.stringBuilder.append("[" + (i + 1) + "] ");
			this.stringBuilder.append(this.options.get(i));
			this.stringBuilder.append(CLI.NEWLINE);
		}
		
		this.stringBuilder.trimToSize();
	}
	
	public T getOption(int index) throws ArrayIndexOutOfBoundsException {
		return this.options.get(index);
	}
	
	public T getSelectedOption() {
		return this.selectedOption;
	}
	
	public T prompt() throws NumberFormatException, ArrayIndexOutOfBoundsException {
		System.out.print(this);
		int option = this.inputWidget.promptForInteger();
		
		if (option < 1 || option > this.options.size()) {
			System.out.println("Invalid Input");
			return this.prompt();
		}
		else {
			this.selectedOption = this.getOption(option - 1);
			return this.selectedOption;
		}
	}
	
	@Override
	public String toString() {
		return this.stringBuilder.toString();
	}
}
